var app = getApp();
// pages/cart/cart.js
Page({
  data:{
    imageUrlFix: app.d.imageUrlFix,
    page:1,
    minusStatuses: ['disabled', 'disabled', 'normal', 'normal', 'disabled'],
    total: 0,
    carts: [],
    count: 0,
    selectCarts: {},//保存选择到的数据
  },

bindMinus: function(e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.carts[index].goods_number;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num --;
    }
    var cart_id = e.currentTarget.dataset.cartid;
    app.request("WxOrderController", "updateCartGoodsNumber", {
      uid: app.d.userId,
      num: num,
      rec_id: cart_id
    }, function (data) {
      // 只有大于一件的时候，才能normal状态，否则disable状态
      var minusStatus = num <= 1 ? 'disabled' : 'normal';
      // 购物车数据
      var carts = that.data.carts;
      carts[index].goods_number = num;
      // 按钮可用状态
      var minusStatuses = that.data.minusStatuses;
      minusStatuses[index] = minusStatus;
      // 将数值与状态写回
      that.setData({
        minusStatuses: minusStatuses
      });
      that.sum();
    });
    // wx.request({
    //   url: app.d.ceshiUrl + '/Api/Shopping/up_cart',
    //   method:'post',
    //   data: {
    //     user_id: app.d.userId,
    //     num:num,
    //     cart_id:cart_id
    //   },
    //   header: {
    //     'Content-Type':  'application/x-www-form-urlencoded'
    //   },
    //   success: function (res) {
    //     var status = res.data.status;
    //     if(status==1){
    //       // 只有大于一件的时候，才能normal状态，否则disable状态
    //       var minusStatus = num <= 1 ? 'disabled' : 'normal';
    //       // 购物车数据
    //       var carts = that.data.carts;
    //       carts[index].num = num;
    //       // 按钮可用状态
    //       var minusStatuses = that.data.minusStatuses;
    //       minusStatuses[index] = minusStatus;
    //       // 将数值与状态写回
    //       that.setData({
    //         minusStatuses: minusStatuses
    //       });
    //       that.sum();
    //     }else{
    //       wx.showToast({
    //         title: '操作失败！',
    //         duration: 2000
    //       });
    //     }
    //   },
    //   fail: function() {
    //     // fail
    //     wx.showToast({
    //       title: '网络异常！',
    //       duration: 2000
    //     });
    //   }
    // });
},

bindPlus: function(e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.carts[index].goods_number;
    var cart_id = e.currentTarget.dataset.cartid;
    if (num < that.data.carts[index].stock) {
      // 自增
      num++;
      app.request("WxOrderController", "updateCartGoodsNumber", {
        uid: app.d.userId,
        num: num,
        rec_id: cart_id
      }, function (data) {
        // 只有大于一件的时候，才能normal状态，否则disable状态
        var minusStatus = num <= 1 ? 'disabled' : 'normal';
        // 购物车数据
        var carts = that.data.carts;
        carts[index].goods_number = num;
        // 按钮可用状态
        var minusStatuses = that.data.minusStatuses;
        minusStatuses[index] = minusStatus;
        // 将数值与状态写回
        that.setData({
          minusStatuses: minusStatuses
        });
        that.sum();
      });
    }else {
      that.setData({
        toastText: "库存不足",
        tips_icon:'/images/tips_icon3.png',
      })
      that.dialog.showDialog();
    }
    // wx.request({
    //   url: app.d.ceshiUrl + '/Api/Shopping/up_cart',
    //   method:'post',
    //   data: {
    //     user_id: app.d.userId,
    //     num:num,
    //     cart_id:cart_id
    //   },
    //   header: {
    //     'Content-Type':  'application/x-www-form-urlencoded'
    //   },
    //   success: function (res) {
    //     var status = res.data.status;
    //     if(status==1){
    //       // 只有大于一件的时候，才能normal状态，否则disable状态
    //       var minusStatus = num <= 1 ? 'disabled' : 'normal';
    //       // 购物车数据
    //       var carts = that.data.carts;
    //       carts[index].num = num;
    //       // 按钮可用状态
    //       var minusStatuses = that.data.minusStatuses;
    //       minusStatuses[index] = minusStatus;
    //       // 将数值与状态写回
    //       that.setData({
    //         minusStatuses: minusStatuses
    //       });
    //       that.sum();
    //     }else{
    //       wx.showToast({
    //         title: '操作失败！',
    //         duration: 2000
    //       });
    //     }
    //   },
    //   fail: function() {
    //     // fail
    //     wx.showToast({
    //       title: '网络异常！',
    //       duration: 2000
    //     });
    //   }
    // });
}, 

  bindManual: function (e) {
  var that = this;
  var index = parseInt(e.currentTarget.dataset.index);
  var num = e.detail.value;
  var oldNum = that.data.carts[index].goods_number;
  if(num < 1){
    wx.showToast({
      title: '商品数量不能小于1',
    })
  }
  var cart_id = e.currentTarget.dataset.cartid;
  if (num <= that.data.carts[index].stock){
    app.request("WxOrderController", "updateCartGoodsNumber", {
      uid: app.d.userId,
      num: num,
      rec_id: cart_id
    }, function (data) {
      // 只有大于一件的时候，才能normal状态，否则disable状态
      var minusStatus = num <= 1 ? 'disabled' : 'normal';
      // 购物车数据
      var carts = that.data.carts;
      carts[index].goods_number = num;
      // 按钮可用状态
      var minusStatuses = that.data.minusStatuses;
      minusStatuses[index] = minusStatus;
      // 将数值与状态写回
      that.setData({
        minusStatuses: minusStatuses
      });
      that.sum();
    });
  }else {
    // wx.showToast({
    //   title: '库存不足',
    // })    
    var carts = that.data.carts;
    carts[index].goods_number = oldNum;
    that.setData({
      carts: carts,
      toastText: "库存不足",
      tips_icon: '/images/tips_icon3.png',
    })
    that.dialog.showDialog();
  }
},


bindCheckbox: function(e) {
  /*绑定点击事件，将checkbox样式改变为选中与非选中*/
  //拿到下标值，以在carts作遍历指示用
  var index = parseInt(e.currentTarget.dataset.index);
  //原始的icon状态
  var selected = this.data.carts[index].selected;
  var carts = this.data.carts;
  var cartsNum = carts.length;
  var selectedItems = this.data.selectCarts;
  // 对勾选状态取反
  carts[index].selected = !selected;
  selectedItems["c" + carts[index]["rec_id"]] = carts[index].selected;
  // 写回经点击修改后的数组
  this.setData({
    carts: carts,
    selectCarts: selectedItems,//保存原本选择的数据
  });
  for (var i = 0; i < cartsNum; i++) {
    if (carts[i].selected) {
      if (i == cartsNum-1) {
        this.setData({
          selectedAllStatus: true
        });
      }
    } else {
      this.setData({
        selectedAllStatus: false
      });
      break;
    }
  };
  // //计算选中的数量
  // var count = 0;
  // for (var j = 0; j < cartsNum; j++){
  //   if (carts[j].selected) {
  //     count++;
  //   } 
  // };
  // this.setData({
  //   count: count
  // });
  this.sum()
},

bindSelectAll: function() {
   // 环境中目前已选状态
   var selectedAllStatus = this.data.selectedAllStatus;
   // 取反操作
   selectedAllStatus = !selectedAllStatus;
   // 购物车数据，关键是处理selected值
   var carts = this.data.carts;

   var selectedItems = this.data.selectCarts;
   // 遍历
   for (var i = 0; i < carts.length; i++) {
     carts[i].selected = selectedAllStatus;
     selectedItems["c" + carts[i]["rec_id"]] = carts[i].selected;
   }
  //  if(selectedAllStatus){
  //   this.setData({
  //     count: carts.length,
  //   });
  //  }else {
  //    this.setData({
  //      count: 0,
  //    });
  //  }
   this.setData({
     selectedAllStatus: selectedAllStatus,
     carts: carts,
     selectCarts: selectedItems,
   });
   this.sum()
 },

bindCheckout: function() {
   // 初始化toastStr字符串
   var toastStr = '';
   // 遍历取出已勾选的cid
   for (var i = 0; i < this.data.carts.length; i++) {
     if (this.data.carts[i].selected) {
       toastStr += this.data.carts[i].rec_id;
       toastStr += ',';
     }
   }
   if (toastStr==''){
     wx.showToast({
       title: '请选择要结算的商品！',
       duration: 2000
     });
     return false;
   }
   //存回data
   wx.navigateTo({
     url: '../order/pay?cartId=' + toastStr,
   })
 },

bindToastChange: function() {
   this.setData({
     toastHidden: true
   });
 },

sum: function() {
    var carts = this.data.carts;
    // 计算总金额
    var total = 0;
    var count = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].goods_number * carts[i].goods_price;
        count ++;
      }
    }
    total = Math.round(total*100)/100;
    // 写回经点击修改后的数组
    this.setData({
      carts: carts,
      total: '¥ ' + total,
      count: count,
    });
  },

//重新获取数据并保存原来数据
refreshData:function(){
  var that = this;
  var selectedItems = that.data.selectCarts;
  var total = 0;//总金额
  var count = 0;//总数
  app.request("WxOrderController", "shoppingList", {
    uid: app.d.userId
  }, function (data) {
    var cart = data.cart;
    if(cart != null && cart.length > 0){
      for (let i = 0; i < cart.length; i++) {
        var cartItemSelected = selectedItems["c" + cart[i]["rec_id"]];
        if (cartItemSelected){
          cart[i].selected = cartItemSelected;
          total += cart[i].goods_number * cart[i].goods_price;
          count ++;
        }
      }
    }
    if(count == cart.length){
      that.setData({
        selectedAllStatus: true,
      })
    }else {
      that.setData({
        selectedAllStatus: false,
      })
    }
    that.setData({
      carts: cart,
      seleceCarts: selectedItems,
      total: '￥' + total,
      count: count,
    })
  });
},
onReady:function(){
  //获得dialog组件
  this.dialog = this.selectComponent("#dialog");
},

onLoad:function(options){
  this.loadProductData();
},

onShow:function(){
  // this.loadProductData();
  //重新获取数据并显示原来已选过的选项
  this.refreshData();
},

touchS: function (e) {
  // console.log("touchS" + e);
  // //判断是否只有一个触摸点
  // if (e.touches.length == 1) {
  //   this.setData({
  //     //记录触摸起始位置的X坐标
  //     startX: e.touches[0].clientX
  //   });
  // }
},

touchM: function (e) {
  // console.log("touchM:" + e);
  // var that = this
  // if (e.touches.length == 1) {
  //   //记录触摸点位置的X坐标
  //   var moveX = e.touches[0].clientX;
  //   //计算手指起始点的X坐标与当前触摸点的X坐标的差值
  //   var disX = that.data.startX - moveX;
  //   //delBtnWidth 为右侧按钮区域的宽度
  //   var delBtnWidth = that.data.delBtnWidth;
  //   var txtStyle = "";
  //   if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
  //     txtStyle = "left:0px";
  //   } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
  //     txtStyle = "left:-" + disX + "px";
  //     if (disX >= delBtnWidth) {
  //       //控制手指移动距离最大值为删除按钮的宽度
  //       txtStyle = "left:-" + delBtnWidth + "px";
  //     }
  //   }
  //   //获取手指触摸的是哪一个item
  //   var index = e.currentTarget.dataset.index;
  //   var list = that.data.carts;
  //   //将拼接好的样式设置到当前item中
  //   list[index].txtStyle = txtStyle;
  //   //更新列表的状态
  //   this.setData({
  //     carts: list
  //   });
  // }
},
touchE: function (e) {
  // console.log("touchE" + e);
  // var that = this
  // if (e.changedTouches.length == 1) {
  //   //手指移动结束后触摸点位置的X坐标
  //   var endX = e.changedTouches[0].clientX;
  //   //触摸开始与结束，手指移动的距离
  //   var disX = that.data.startX - endX;
  //   var delBtnWidth = that.data.delBtnWidth;
  //   //如果距离小于删除按钮的1/2，不显示删除按钮
  //   var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
  //   //获取手指触摸的是哪一项
  //   var index = e.currentTarget.dataset.index;
  //   var list = that.data.carts;
  //   list[index].txtStyle = txtStyle;
  //   //更新列表的状态
  //   that.setData({
  //     carts: list
  //   });
  // }
},

removeShopCard:function(e){
    var that = this;
    var cardId = e.currentTarget.dataset.cartid;
    wx.showModal({
      title: '提示',
      content: '你确认移除吗',
      success: function(res) {
        res.confirm && app.request("WxOrderController", "delCart", {
          rec_id: cardId
        }, function (data) {
          that.refreshData();
        });
        
        // wx.request({
        //   url: app.d.ceshiUrl + '/Api/Shopping/delete',
        //   method:'post',
        //   data: {
        //     cart_id: cardId,
        //   },
        //   header: {
        //     'Content-Type':  'application/x-www-form-urlencoded'
        //   },
        //   success: function (res) {
        //     //--init data
        //     var data = res.data;
        //     if(data.status == 1){
        //       //that.data.productData.length =0;
        //       that.loadProductData();
        //     }else{
        //       wx.showToast({
        //         title: '操作失败！',
        //         duration: 2000
        //       });
        //     }
        //   },
        // });
      },
      fail: function() {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },

// 数据案例
  loadProductData:function(){
    var that = this;
    app.request("WxOrderController", "shoppingList", {
      uid: app.d.userId
    }, function (data) {
      var cart = data.cart;
      that.setData({
        carts: cart,
        selectedAllStatus: false,
      });
      that.sum();
    });
  
    // wx.request({
    //   url: app.d.ceshiUrl + '/Api/Shopping/index',
    //   method:'post',
    //   data: {
    //     user_id: app.d.userId
    //   },
    //   header: {
    //     'Content-Type':  'application/x-www-form-urlencoded'
    //   },
    //   success: function (res) {
    //     //--init data
    //     var cart = res.data.cart;
    //     that.setData({
    //       carts:cart,
    //     });
    //     //endInitData
    //   },
    // });
  },
})